﻿using System;
using System.Windows;
using System.Windows.Markup;

namespace Zuehlke.Blueprint.Quickstart.Architecture.Presentation.UserInterface.Extensions
{
    /// <summary>
    /// Helper class to be used for initializing a view at the right moment (see <see cref="RegisterForLateInitialize{TView}"/> for details).
    /// </summary>
    public static class ViewInitializationHelperExtension
    {
        /// <summary>
        /// Registers a view to be late initialized which means that the view's InitializeComponent method is executed AFTER the logical parent
        /// has been set.
        /// This ensures that e.g. bindings are evaluated when the full logical parent tree is present avoiding the multiple evaluation of bindings.
        /// </summary>
        public static void RegisterForLateInitialize<TView>(this TView view)
            where TView : FrameworkElement, IComponentConnector
        {
            if (view.IsInitialized)
            {
                view.InitializeComponent();
                return;
            }

            new InitializeContext<TView>(view);
        }

        private class InitializeContext<TView>
            where TView : FrameworkElement, IComponentConnector
        {
            private readonly TView _view;

            public InitializeContext(TView view)
            {
                _view = view;
                _view.Initialized += OnViewInitialized;
            }

            private void OnViewInitialized(object sender, EventArgs args)
            {
                _view.Initialized -= OnViewInitialized;
                _view.InitializeComponent();
            }
        }
    }
}
